package com.harmontronics.hanma.paas.paas.interceptor;

import com.harmontronics.hanma.paas.paas.annotation.TokenValidSkip;
import com.harmontronics.hanma.paas.paas.exception.TokenErrorException;
import com.harmontronics.hanma.paas.paas.token.AppUserTokenKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ldb
 */
public class AppTokenValidInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AppUserTokenKit appUserTokenKit;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        HandlerMethod method = (HandlerMethod) handler;
        TokenValidSkip tokenValidSkip = method.getMethodAnnotation(TokenValidSkip.class);
        if (tokenValidSkip != null) {
            return true;
        }
        try {
            appUserTokenKit.renew();
        }catch (TokenErrorException ex){
            response.setStatus(ex.getStatus());
            return false;
        }

        return true;
    }

}
